<?php

namespace app\controller;

use support\Request;
use support\Response;

class TransController
{
    public function index(Request $request) : ? Response
    {
        $return = $input = [
            'q' => $request->input('q'),
            'to'=> $request->input('to','英语'),
        ];
        $returnArr = $this->_curl($this->_get_param($input));
        $return['v'] = empty($returnArr) ? '' : join('', $returnArr);
        return json(['code'=>0,'data'=>$return]);
    }

    private function _get_param($input) {
        $messages = [
            ['role'=>'system','content'=>'请担任翻译官，将中文翻译为'.$input['to'].'，英文翻译为中文。'],
            ['role'=>'assistant', 'content'=>'翻译'],
            ['role'=>'user', 'content'=> $input['q'] ],
        ];

        $param = [
            'max_tokens'    => 2000,
            'temperature'   => 0.5,
            'stream'        => true,
            'messages'      => $messages,
            'model'         => 'gpt-3.5-turbo-16k',
            'user_message_id'=> '1697263896290739',
            'assistant_message_id' => '169726389629043',
            'role_id'       => 5,
        ];
        return $param;
    }

    private function _curl($param) {
        $jsonStr = json_encode($param);
        /* 建立接收的Temp File Stream */
        $tmpfile = tmpfile ();

        // 初始化curl会话
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        // 设置curl会话参数
        curl_setopt($ch, CURLOPT_URL, 'https://ai.tlang.com/app/ai/message/send'); // 设置请求URL
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36');
        curl_setopt($ch ,CURLOPT_FILE, $tmpfile );
        //curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true); // 设置请求方式为POST
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 500);
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); // 设置cookie保存的文件名
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // 设置cookie读取的文件名

        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        // 执行curl请求
        /* 执行并取得状态*/
        $status = curl_exec ( $ch );
        curl_close ( $ch );

        if (! $status ){
            fclose ( $tmpfile );
            exit ( 'error' );
        }

        /* Temp File Stream 指标归零*/
        fseek ( $tmpfile , 0);

        $return = [];
        /*一次读取一行*/
        while (( $line = fgets ( $tmpfile )) !== false ) {
            $_cnt = $this->_format(trim($line));
            !empty($_cnt) && $return[] = $_cnt;
        }

        /* 关闭Stream */
        fclose ( $tmpfile );

        return $return;
    }

    private function _format($str) {
        $return = '';
        $json = json_decode(str_replace('data: {', '{', $str), true);var_dump($str);
        if ($json && isset($json['choices'])) {
            $delta = $json['choices'][0]['delta'];
            $return = $delta ? $json['choices'][0]['delta']['content'] : '';
        }
        return $return;
    }
}